var express = require('express');
var router = express.Router();
var utils = require('../functions/utils');

router.post('/', function(req,res)
{
/*
	Input parameters 

	 *  	sessionId			like user session
	 *		articleId			아티클ID
*/
	var sessionId = req.body.sessionId;			utils.checkParamValue( 'sessionId' , sessionId);
	var articleId = req.body.articleId;			utils.checkParamValue( 'articleId' , articleId);

	utils.callLog(req);

	utils.sessionTraceLog(req);


	var async = require('async');
	async.waterfall([
		function(cb)
		{
			utils.getUserIdWithSessionId(sessionId , cb);
		}
		,function(userId , cb) {
			if(!userId)
			{
				var err = new Error('Invalid session ID : ' + sessionId);
				err.code = '522';
				throw err;
			}

			///////////////////////////본 루틴//////////////////////////////


			// update, insert 하는 항목이 있으므로 master
			global.master_db.connection.getConnection(function(err,connection)
			{
				if(err)
				{
					throw err;
				}


				var input_param = [userId , articleId];

				var sql = 'call api_like(? , ? , @userName , @userKey , @result);';
				sql += 'SELECT @userName AS userName, @userKey AS userKey, @result AS result';

				var query = connection.query(sql, input_param , function (err, rows) 
				{
					connection.release();
					if(err)
					{
						throw err;
					}

					var result = null;
					// 202 이외
					if(rows.length == 2)
						result = rows[1][0].result;
					// 202
					else
						result = rows[2][0].result;

					var ret = {};	 // 기본값은 성공


					switch(result)
					{
						case 202:
							ret.code = '202';
							break;
						case 271:
							var err = new Error('Already liked this article : ' +sessionId + ',' +  articleId);
							err.code = '271';
							throw err;
							break;
						case 523:
							var err = new Error('Invalid ArticleId : ' + articleId);
							err.code = '523';
							throw err;
							break;
						default:
							throw new Error();

					}

					// 응담먼저 보내고 
					res.json(ret);
					res.end();

					// push 작업 - 성공이고 pushkey list가 넘어왔을 경우
					if(rows.length == 3 && utils.isValidArray(rows[0]))
					{
						var pushList = [];
						for(var i = 0 ; i < rows[0].length ; i ++)
						{
							var pushInfo = {};

							// 모든 푸시 공통 (token , endpointArn , appId , badge , msgid , msgType)
							pushInfo = rows[0][i];

							// 푸시케이스에 따라 다른 것들 
							pushInfo.message = rows[2][0].userName + ' loves your video!';
							pushInfo.sound = false; //사운드 안나옴.

							pushInfo.userKey = rows[2][0].userKey;
							pushInfo.articleId = articleId;

							pushList[i] = pushInfo;

						}

						// 푸시 날린다.
						var push = require('../functions/cbPush');
						push(pushList);

					}


				}); // query

			}); //get connection

			////////////////////////////////////////////////////////////////////////

		}
	]); //waterfall


}); // router

module.exports = router;